package example.servlet;

import javax.servlet.AsyncContext;
import javax.servlet.ServletException;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 支持异步请求的servlet
 */
@WebServlet(value = "/async", asyncSupported = true)
public class AsyncServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        System.out.println(Thread.currentThread().getName() + " 主线程 start...");
        AsyncContext asyncContext = req.startAsync();
        //asyncContext.setTimeout(2000); 设置超时
        asyncContext.start(new Runnable() {
            @Override
            public void run() {
                try {
                    System.out.println(Thread.currentThread().getName() + "子线程 start...");
                    Thread.sleep(5000);
                    //处理完成
                    asyncContext.complete();
                    ServletResponse response = asyncContext.getResponse();
                    response.getWriter().write("异步请求完成！");
                    System.out.println(Thread.currentThread().getName() + " 子线程 end...");

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
        System.out.println(Thread.currentThread().getName() + " 主线程 end...");

    }




}




